<?php
/**
 * 提成管理控制器
 */

namespace app\admin\controller;

use app\common\model\Department;
use app\common\model\Staff;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Request;
use app\common\model\Commission;

use app\common\validate\CommissionValidate;

class CommissionController extends Controller
{

    //列表
    public function index(Request $request, Commission $model)
    {
        $param = $request->param();

        $where1 = [];
        if (!empty($param['commission_time']) ) {
            $where1['commission_time'] = strtotime($param['commission_time']);
        }
        $where = [];
        if (!empty($param['staff_id'])){
            $where['id']=$param['staff_id'];
        }

        if (!empty($param['department_id'])) {
            $where['department_id']=$param['department_id'];
        }
        $order = $param['_order'] ?? '';
        $by    = $param['_by'] ?? '';
        $model = $model->hasWhere('staff',$where)->with(['staff'=>function($query){
            $query->with(['department','insure']);
        }])->where($where1)->order($order ?: '', $by ?: '')->order('department_id','DESC');
//        $data = $model->fetchSql(true)->select();
//        dump($data);die;
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['员工ID','部门ID', '姓名', '部门', '提成时间', '业绩完成', '部门提成', '医院打蜡补助', '推荐奖金', '补发提成', '助成交提成', '专家提成', '会场补助','其他补助','备注', '提成合计',  '状态1启用0禁用'];
            $body = [];
            $data = $model->select();
            foreach ($data as $item) {
                $record = [];
                $record['staff_id'] = $item->staff_id;
                $record['department_id'] = $item->staff->department_id;
                $record['staff_name'] = $item->staff->name;
                $record['department_name'] = $item->staff->department->name;
                $record['commission_time'] = $item->commission_time;
                $record['completion'] = $item->completion;
                $record['department_commission'] = $item->department_commission;
                $record['hos_wax_subsidy'] = $item->hos_wax_subsidy;
                $record['recommend_bonus'] = $item->recommend_bonus;
                $record['reissue_commission'] = $item->reissue_commission;
                $record['help_commission'] = $item->help_commission;
                $record['expert_commission'] = $item->expert_commission;
                $record['meeting_subsidy'] = $item->meeting_subsidy;
                $record['other_subsidy'] = $item->other_subsidy;
                $record['remarks'] = $item->remarks;
                $record['total_commission'] = $item->total_commission;
                $record['status'] = $item->status;

                $body[] = $record;
            }
            return $this->exportData($header, $body, '提成-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query' => $request->get()]);

        if (isset($param['department_id']) && !empty($param['department_id'])) {
            $demodel = Department::get($param['department_id']);

            $this->assign('department_list', $this->getSelectList($demodel, $param['department_id']));
        } else {
            $this->assign('department_list', $this->getSelectList(new Department));
        }
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'staff_list' => Staff::all(),
            'data' => $data,
            'page' => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, Commission $model, CommissionValidate $validate)
    {
        if ($request->isPost()) {
            $param = $request->param();
            $arrs = ['completion','department_commission','hos_wax_subsidy','recommend_bonus','reissue_commission','help_commission','expert_commission','meeting_subsidy'];
            $param['total_commission'] = 0;
            foreach ($param as $key => $value){
                if (in_array($key,$arrs) && $value != ''){
                    $param['total_commission'] += round($value,2);
                }
            }
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理附件上传
            if (!empty($_FILES['file']['name'][0])) {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }


            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功', $url) : error();
        }
        $this->assign([
            'department_list' => $this->getSelectList(new Department),
            'staff_list' => Staff::all()
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, Commission $model, CommissionValidate $validate)
    {

        $data = $model::where('id', $id)->with('staff')->find();
        if ($request->isPost()) {
            $param = $request->param();
            $arrs = ['completion','department_commission','hos_wax_subsidy','recommend_bonus','reissue_commission','help_commission','expert_commission','meeting_subsidy'];
            $param['total_commission'] = 0;
            foreach ($param as $key => $value){
                if (in_array($key,$arrs) && $value != ''){
                    $param['total_commission'] += round($value,2);
                }
            }
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理附件上传
            if (!empty($_FILES['file']['name'][0])) {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }


            $result = $data->save($param);
            return $result ? success() : error();
        }
        if ($data->staff->department){
            $this->assign(
                ['department_list' => $this->getSelectList($data->staff->department, $data->staff->department->id)]
            );
        }else{
            $this->assign([
                'department_list' => $this->getSelectList(new Department),
            ]);
        }
        $this->assign([
            'data' => $data,
            'staff_list' => Staff::all(),
        ]);
        return $this->fetch('add');

    }

    //删除
    public function del($id, Commission $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //启用
    public function enable($id, Commission $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


//禁用
    public function disable($id, Commission $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


    //新建用户绩效按月排除重复
    public function nameUnique(Request $request, Commission $commission)
    {
        $params = $request->param();
        if (isset($params['commission_time'])) {
            $params['commission_time'] = strtotime($params['commission_time']);
            $params['staff_id'] = intval($params['staff_id']);
        }
        $count = $commission->where($params)->count();
        if ($count > 0) {
            return error('您的名称重复，请重新输入');
        } else {
            return success('细项可用');
        }
    }

    //excel导入入库
    public function importData(Request $request, Commission $commission)
    {
        ini_set('max_execution_time','0');
        $params = $request->param();
        $commission_data = [];
        if (isset($params['commission_time'])) {
            $commission_time = strtotime($params['commission_time']);
            $commission_data = Commission::where('commission_time', $commission_time)->column('staff_id', 'id');
        } else {
            return json_encode(['code' => 0, 'msg' => '请先选择时间']);

        }
        //获取表格的大小，限制上传表格的大小5M

        $file_size = $_FILES['commission']['size'];
        if ($file_size > 30 * 1024 * 1024) {
            $this->error('文件大小不能超过30M');
            exit();
        }

        //限制上传表格类型
        $fileExtendName = substr(strrchr($_FILES['commission']["name"], '.'), 1);
        //application/vnd.ms-excel  为xls文件类型
        if ($fileExtendName != 'xlsx' && $fileExtendName != 'xls') {
            $this->error('表格必须为xlsx或xls格式！');
            exit();
        }
        $header1 = ['员工ID','部门ID', '姓名', '部门', '提成时间', '业绩完成', '部门提成', '医院打蜡补助', '推荐奖金', '补发提成', '助成交提成', '专家提成', '会场补助','其他补助','备注', '提成合计',  '状态1启用0禁用'];
        $header = ['staff_id', 'department_id', 'staff_name', 'department_name', 'commission_time', 'completion', 'department_commission', 'hos_wax_subsidy', 'recommend_bonus','reissue_commission','help_commission','expert_commission','meeting_subsidy','other_subsidy','remarks','total_commission','status'];
        if (is_uploaded_file($_FILES['commission']['tmp_name'])) {
            // 有Xls和Xlsx格式两种
            if ($fileExtendName === 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $spreadsheet = $objReader->load($_FILES['commission']['tmp_name']);
            $sheetData = $spreadsheet->getActiveSheet()->ToArray();
            $datas = [];
            $header2 = $sheetData[0];
            if ($header2 !== $header1) {
                return json_encode(['code' => 0, 'msg' => '表格格式不正确']);
            }
            $msg = "";
            foreach ($sheetData as $key => $value) {
                if ($key > 0) {
                    foreach ($value as $k => $v) {
                        if ($header[$k] === 'commission_time' && strtotime($v) != $commission_time) {
                            $msg .= $value[2]." : 时间格式不正确<br>";
                            unset($datas[$key]);
                            break;
                        }
                        if ($header[$k] === 'staff_id' && in_array($v, $commission_data)) {
                            $datas[$key]['id'] = array_search($v, $commission_data);
                        }
                        $datas[$key][$header[$k]] = $v ?? '';
                    }
                }
            }

            Db::startTrans();
            try {
                $commission->saveAll($datas);
                Db::commit();
                return json_encode(['code' => 1, 'msg' => $msg]);

            } catch (\Exception $e) {
                Db::rollback();
            }

        } else {
            return json_encode(['code' => 0, 'msg' => $_FILES['commission']['name'] . '文件上传失败 ']);
        }
    }

}
